package com.xjh.him.core.netty.codec;

import com.alibaba.fastjson.JSON;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * 消息解码器
 */
public class MsgDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() > 0) {
            list.add(decode(byteBuf));
        }
    }

    private Object decode(ByteBuf in) {
        in.skipBytes(1); // MAGIC_NUM
        byte command = in.readByte();
        Class<?> clazz = Command.getClazz(command);
        int len = in.readInt();
        byte[] bs = new byte[len];
        in.readBytes(bs);
        return JSON.parseObject(new String(bs), clazz);
    }
}
